﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
//using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Permissions;
using System.Drawing.Design;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.ComponentModel.Design;

namespace jQuery.WebControls.RocketDock
{
    /// <summary>
    /// Control Web personalizado que crea un menu en forma de barra al estilo
    /// del sistema operativo Mac con jQuery.    
    /// </summary>
    [AspNetHostingPermission(SecurityAction.Demand,
        Level = AspNetHostingPermissionLevel.Minimal),
    AspNetHostingPermission(SecurityAction.InheritanceDemand,
        Level = AspNetHostingPermissionLevel.Minimal),
    DefaultProperty("Icons"),   
    ToolboxData("<{0}:RocketDockMenu runat=server></{0}:RocketDockMenu>"),
    Designer(typeof(RocketDockDesigner)),Serializable()]
    public class RocketDockMenu : WebControl, INamingContainer
    {
        private ClientScriptProxy scriptManager;
        private List<Icono> icons;
        private string advertencias = "";
        private jQueryScriptManager jQueryMngr;

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            if (!Page.IsPostBack)
            {
                if (!DesignMode)
                    CheckQueryManager();
            }
        }

        /// <summary>
        /// Se comprueba que esten todos los requisitos necesarios
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            
        }
        
        #region "PROPIEDADES PRIVADAS"       
        private string IdDockClient { get { return "m" + ClientID; } }
        #endregion

        #region "PROPIEDADES"
        /// <summary>
        /// Coleccion de Icons para añadir a RocketDockMenu
        /// </summary>
        [Category("Data")]
        [Description("Lista de controles ImagButton que se van a mostrar en el menu")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
        Editor(typeof(CollectionEditor), typeof(UITypeEditor))]
        [PersistenceMode(PersistenceMode.InnerProperty)]        
        public List<Icono> Icons
        {
            get
            {
                if (icons == null)
                {
                    icons = new List<Icono>();                    
                }
                return icons;
            }
        }
        
        /// <summary> 
        /// Ancho de los Icons del menu cuando el puntero no esta sobre ellos
        /// </summary>        
        [Category("Appearance")]
        [DefaultValue("48px")]
        [Localizable(false)]
        [Description("Ancho de los Icons cuando el cursor no esta encima de ellos")]
        public Unit MinimumWidth
        {
            get
            {
                if (ViewState["Wmin"] == null)
                    ViewState["Wmin"] = new Unit(48, UnitType.Pixel);
                return (Unit)ViewState["Wmin"];
            }
            set
            {
                ViewState["Wmin"] = value;
            }
        }

        /// <summary>
        /// Ancho de los Icons del menu cuando el puntero esta sobre ellos
        /// </summary>        
        [Category("Appearance")]
        [DefaultValue("64px")]
        [Localizable(false)]
        [Description("Ancho de los Icons cuando el cursor esta encima de ellos")]
        public Unit MaximumWidth
        {
            get
            {
                if (ViewState["Wmax"] == null)
                    ViewState["Wmax"] = new Unit(48, UnitType.Pixel);
                return (Unit)ViewState["Wmax"];
            }

            set
            {
                ViewState["Wmax"] = value;
            }
        }

        /// <summary>
        /// Altura de la capa DIV que contiene el menu
        /// </summary>
        [Category("Appearance")]
        [DefaultValue("115px")]
        [Localizable(false)]
        [Description("Altura del Fondo de la Barra Dock")]
        public Unit HeightDock
        {
            get
            {
                if (ViewState["Hdock"] == null)
                    ViewState["Hdock"] = new Unit(115, UnitType.Pixel);
                return (Unit)ViewState["Hdock"];
            }

            set
            {
                ViewState["Hdock"] = value;
            }
        }

        /// <summary>
        /// Distancia del icono al cursor a partir del cual comienza a agrandarse hasta el ancho maximo
        /// </summary>
        [Category("Appearance"),
        DefaultValue("50px"),
        Localizable(false),
        Description("Distancia del icono al cursor a partir del cual comienza a agrandarse hasta el ancho maximo")]
        public Unit Proximity
        {
            get
            {
                if (ViewState["prx"] == null)
                    ViewState["prx"] = new Unit(50, UnitType.Pixel);
                return (Unit)ViewState["prx"];
            }

        }

        /// <summary>
        /// Imagen de fondo que se repite en el eje X
        /// </summary>
        [DefaultValue("")]
        [Category("Appearance"), 
        Editor("System.Web.UI.Design.UrlEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))]
        [Description("Imagen de fondo donde se colocaran los Icons. La imagen solo se repite en el eje x")]
        public string BackgroundImage
        {
            get
            {
                String s = (String)ViewState["BackG"];
                return ((s == null) ? "" : s);
            }
            set
            {
                ViewState["BackG"] = value;
            }
        }
        
        #endregion

        /// <summary>
        /// Crea la colección de controles HTML, estilos Css y scripts necesarios para generar el RocketDockMenu
        /// </summary>
        protected override void CreateChildControls()
        {
            string html = "<!--INICIO:RocketDocketMenuWeb-->" + getRenderStyles();
            html += "<div id=\"barraDock" + IdDockClient + "\" style=\"padding-top:10px\">" +
                "   <div class=\"dock\" id=\"" + IdDockClient + "\" >" +
                "       <div class=\"dock-container\">";

            this.Controls.Add(new LiteralControl(html));

            for (short i = 0; i < Icons.Count; i++)
            {
                Icons[i].CssClass = "dock-item";
                this.Controls.Add(Icons[i]);                
            }
            html = "</div></div></div>" + getRenderAdvertencias();
            html += getRenderScripts() + "<!--FIN:RocketDocketMenuWeb-->";
            this.Controls.Add(new LiteralControl(html));
        }

        #region "RENDER"
        private string getRenderStyles()
        {
            string styles = "<style type='text/css'>" +
                "#barraDock" + IdDockClient + "{" +
                "   background-image: url(" + Page.ResolveUrl(BackgroundImage) + ");" +
                "   background-repeat: repeat-x;" +
                "   background-color: " + (System.Drawing.ColorTranslator.ToHtml(this.BackColor) != string.Empty ? System.Drawing.ColorTranslator.ToHtml(this.BackColor) : "transparent") + ";" +
                "   height: " + HeightDock.ToString() + ";	}" +
                ".dock{" +
                "   position: relative; " +
                "   height: 50px; " +
                "   text-align: center;}" +
                ".dock-container {" +
                "   position: absolute;" +
                "   height: 115px;" +
                "   padding-left: 20px;}" +
                "a.dock-item{" +
                "   display: block; " +
                "   width: 40px;" +
                "   color: #000;" +
                "   position: absolute;" +
                "   top: 0px;" +
                "   text-align: center;" +
                "   text-decoration: none;}" +
                ".dock-item img {" +
                "   border: none; " +
                "   margin: 5px 10px 0px; " +
                "   width: 100%; }" +
                ".dock-item span {" +
                "   display: none; " +
                "   padding-left: 20px;" +
                "   font: " + (Font.Bold ? "bold" : "normal") + " " + Font.Size.ToString() + " " + Font.Name + ";" +
                "   color: " + (System.Drawing.ColorTranslator.ToHtml(ForeColor) != string.Empty ? System.Drawing.ColorTranslator.ToHtml(ForeColor) : "#333") + "}" +
                "</style>";
            return styles;
        }

        private string getRenderScripts()
        {
            string scripts = "<script type='text/javascript'>" +
                    "$(document).ready(" +
                    "function() {" +
                    "$('#" + IdDockClient + "').Fisheye({" +
                    "maxWidth: " + MaximumWidth.Value.ToString() + "," +
                    "items: 'a'," +
                    "itemsText: 'span'," +
                    "container: '.dock-container'," +
                    "itemWidth: " + MinimumWidth.Value.ToString() + "," +
                    "proximity: " + Proximity.Value.ToString() + "," +
                    "alignment: 'left'," +
                    "valign: 'bottom'," +
                    "halign: 'center'})});" +
                    "</script>";
            return scripts;
        }

        private string getRenderAdvertencias()
        {
            string htmlAdv = "";
            if (advertencias.Length > 0)
            {
                string[] aux = advertencias.Split('#');
                htmlAdv = "<div>Advertencias:<ul>";
                for (int i = 0; i < aux.Length; i++)
                {
                    htmlAdv += String.Format("<li style='color:red'>{0}</li>", aux[i]);
                }
                htmlAdv += "</ul></div>";
            }
            return htmlAdv;
        }
        #endregion

        private void AddWarning(string mensaje)
        {
            advertencias += mensaje + "#";
        }

        private ClientScriptProxy ClientScriptProxy
        {
            get
            {
                if (scriptManager == null)
                {
                    scriptManager = ClientScriptProxy.Current;
                }
                return scriptManager; 
            }
        }


        private jQueryScriptManager jQueryManager
        {
            get
            {
                if (jQueryMngr == null)
                    jQueryMngr = Common.Instance.Get_jQueryScriptManager(Page);
                return jQueryMngr;
            }
        }

        private void CheckQueryManager()
        {
            Common.Instance.CheckJQueryScriptManager(Page);
        }
    }
}
